<template>
	<view class="search">
		<search-header :focus="true" @search="search" @back="backIndex"></search-header>
		<common-line/>
		<view class="search-content">
			<view class="search-item">
				<view class="search-title">
					<view>最近搜索</view>
					<view v-if="searchHistory && searchHistory.length > 0" class="iconfont icon-lajitong" @click="removeSearchHistory"></view>
				</view>
				<view>
					<view v-if="searchHistory.length > 0">
						<view
						@tap="searchTag(item)"
								class="search-name"
								v-for="(item,index) in searchHistory"
								:key="index">
							{{ item }}
						</view>
					</view>
					<view class="no-history" v-else>暂无数据</view>
				</view>
			</view>
			
			<!-- <view class="search-item">
				<view class="search-title">
					<view>热门搜索</view>
					<view class="iconfont icon-lajitong"></view>
				</view>
				<view>
					<view class="search-name">四件套</view>
					<view class="search-name">面膜</view>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script>
	import CommonLine from '../../components/common/CommonLine.vue'
	import SearchHeader from '../../components/common/SearchHeader.vue'
	export default {
		components: {
			CommonLine,
			SearchHeader
		},
		data() {
			return {
				searchHistory:[],
			}
		},
		onLoad() {
			let searchHistory = uni.getStorageSync('searchHistory')
			if (searchHistory) {
				this.searchHistory = JSON.parse(searchHistory)
			}
		},
		methods: {
			search(keyword) {
				if(!keyword) {
					uni.showToast({
						icon: 'none',
						title:'请输入需要搜索的商品',
						duration:1000
					})
					return
				}
				this.addToHistory(keyword)
				uni.navigateTo({
					url: '/pages/search-list/search-list?keyword=' + keyword
				})
			},
			searchTag(keyword) {
				uni.navigateTo({
					url: '/pages/search-list/search-list?keyword=' + keyword
				})
			},
			backIndex() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			addToHistory(text) {
				let idx = this.searchHistory.find(item => item === text);
				if (idx) {
					return
				}
				this.searchHistory.push(text)
				uni.setStorage({
					key: 'searchHistory',
					data: JSON.stringify(this.searchHistory)
				})
			},
			removeSearchHistory() {
				this.searchHistory = []
				uni.removeStorageSync('searchHistory')
			}
		}
	}
</script>

<style scoped>
	.search-content {
		padding: 20rpx 20rpx;
	}
	.search-title {
		display: flex;
		justify-content: space-between;
		color: #7F7F7F;
	}
	.search-name {
		padding: 6rpx 20rpx;
		background-color: #F0F2F5;
		border-radius: 10rpx;
		display: inline-block;
		margin: 20rpx;
		color: #686868;
	}
	.no-history {
		margin-top: 20rpx;
		text-align: center;
		color: #7F7F7F;
	}
</style>
